/* main.c */
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2c.h"
#include "esp_log.h"
#include "cw2015.h"

static const char *TAG = "MAIN";

// I2C Configuration
#define I2C_SDA_GPIO 36
#define I2C_SCL_GPIO 35
#define I2C_MASTER_FREQ_HZ      400000

// GPIO Configuration
#define ALRT_PIN                GPIO_NUM_37

/* ---------- 通用 I2C 初始化 ---------- */
static void i2c_master_init(void)
{
    i2c_config_t conf = {
        .mode = I2C_MODE_MASTER,
        .sda_io_num = I2C_SDA_GPIO,
        .scl_io_num = I2C_SCL_GPIO,
        .sda_pullup_en = GPIO_PULLUP_ENABLE,
        .scl_pullup_en = GPIO_PULLUP_ENABLE,
        .master.clk_speed = I2C_MASTER_FREQ_HZ,
    };
    ESP_ERROR_CHECK(i2c_param_config(I2C_PORT, &conf));
    ESP_ERROR_CHECK(i2c_driver_install(I2C_PORT, conf.mode, 0, 0, 0));
}

/* ---------- 应用入口 ---------- */
void app_main(void)
{
    i2c_master_init();                  // 1. 初始化 I2C 外设
    ESP_ERROR_CHECK(cw2015_init());     // 2. 检测 CW2015 是否存在
    ESP_ERROR_CHECK(cw2015_write_battery_profile()); // 3. 一次性烧录模型

    uint32_t volt_mv, cap_cent;         // 单位：mV  0.01%
    while (1) {
        cw2015_update_voltage(&volt_mv);
        cw2015_update_capacity(&cap_cent);

        /* 正确拆分 0.01% -> 整数和小数部分 */
        printf("Battery: %lu mV  %lu.%02lu %%\n",
               volt_mv,
               cap_cent / 100,
               cap_cent % 100);

        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}